package com.wzy.controller;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: wzy
 * @Date: 2021/11/27/11:40
 * @Description:
 */
public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask task = new MyTask(0, 100);
        // 创建分支合并对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        System.out.println(submit.get());
        forkJoinPool.shutdown();
    }

}
class  MyTask extends RecursiveTask<Integer>{
    // 拆分的插值不大于10
    private static final Integer VALUE = 10;
    private  int begin;
    private int end;
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end - begin) <= VALUE){
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        }else {
            // 进一步拆分
            int mid = begin + (end -begin)/2;
            MyTask task01 = new MyTask(begin,mid);
            MyTask task02 = new MyTask(mid+1,end);
            task01.fork();
            task02.fork();
            result = task01.join()+task02.join();
        }
        return result;
    }
}
